﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using ZH.Infrastructure.Attr;
using ZH.Infrastructure.Dto.Request.Login;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Dto.Response.admin;
using ZH.Infrastructure.EFCore.MySql;
using ZH.Infrastructure.IOC;
using ZH.Infrastructure.Redis;
using ZH.Infrastructure.Tools;
using ZH.Service.Interface;

namespace ZH.Service.Instance
{
    [Inject_]
    public class Cashier_Service : Base_Service, I_Cashier_Service
    {
        public readonly Cashier_IOC _cashier_IOC;
        private readonly RedisStringService _redisStringService;
        public readonly IConfiguration _configuration;

        public Cashier_Service(
            Cashier_IOC cashier_IOC,
            IConfiguration configuration,
             RedisStringService redisStringService
            ) {
            _cashier_IOC=cashier_IOC;
            _redisStringService = redisStringService;
            _configuration = configuration;


        }    
        public async Task<Api_Response_Dto> Logins(Login_Request_Dto dto)
        {
            


            var iq = _cashier_IOC._cashier_EFCore.QueryAll(d => d.Caccount == dto.account);
            if (!await iq.AnyAsync())
            {
                return Result(0, "账号或者密码错误！");
            }

            var Cashier = await iq.SingleAsync();
            var pwd = EncryptUtil.LoginMd5(dto.password!, Cashier.Csalt!);
            if (Cashier.Cpassword != pwd)
            {
                return Result(0, "账号或者密码错误！");
            }

            if (Cashier.CisBan == 1)
            {
                return Result(0, "账号已禁用");
            }
            //添加登录日志
            Cashierloginlog cashierloginlog = new Cashierloginlog()
            {
                ClAccount = Cashier.Caccount,
                ClName = Cashier.Cname,
                ClCode = dto.code,
                ClCreateTime = DateTime.Now,
                ClId = Config.GUID(),
                ClIp = Config.GetIp(),
            };
            _cashier_IOC._cashierloginlog_EFCore.Add(cashierloginlog);

            if (Cashier.CisActive == 0)
            {
                Cashier.CisActive = 1;
                _cashier_IOC._cashier_EFCore.Update(Cashier);
            }
            _cashier_IOC._cashier_EFCore.SaveChanges();
            _cashier_IOC._cashierloginlog_EFCore.SaveChanges();
            //事务
            //var result = _supplier_IOC._supplier_Login_log.Transactions(_supplier_IOC._supplier_EFCore);
            //redis 保存code
            if (true)
            {
                //事务成功就是登录完成了 存入redis
                var key = _configuration["Redis:Keys:Cashier_Check_Login"];
                _redisStringService.Set<string>(key + Cashier.Caccount, dto.code!, DateTime.Now.AddSeconds(60 * 60 * 24));//一天有效

            }

            return Result(true ? 1 : 0);
        }

        public User_Response_Dto? Check_Login(string? code, string account)
        {

            var _user = _redisStringService.Get<string>(code!);//获取用户信息

            if (!string.IsNullOrEmpty(_user))//获取到了代表当前code是有效的
            {
                return JsonConvert.DeserializeObject<User_Response_Dto>(_user);
                //直接把信息返回回去即可
            }

            //没有获取到用户信息


            var key = _configuration["Redis:Keys:Cashier_Check_Login"];
  
            var jwt = _redisStringService.Get<string>(key + account);//是否是有效的code 最后一个code
            if (code == jwt)
            {
           
                var user = _cashier_IOC._cashier_EFCore.QueryAll(d => d.Caccount == account).Select(d => new
                User_Response_Dto
                {
                    id = d.Cid,
                    name = d.Cname,
                    account = d.Caccount,
                    isActive = d.CisActive,
                    isBan = d.CisBan,
                    time = d.CcreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).Single();
                _redisStringService.Set(code, JsonConvert.SerializeObject(user), DateTime.Now.AddSeconds(60));
                return user;
            }
            else
                return null;
        }
    }
    }

